package com.aft.terra.common.utils;

import java.io.File;

import org.apache.commons.lang.StringEscapeUtils;
import org.beetl.core.Format;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;

import com.jfinal.kit.PathKit;

/**
 * @author Nishichen
 * Created by yinjun622 on 14-8-11. 
 * xss 如果是html 加上escape
 */
public class XSSDefenseFormat implements Format {

	public Object format(Object data, String pattern) {
		if (null == data) {
			return null;
		} else {
			try {
				String path = PathKit.getRootClassPath() +File.separator +"antisamy.xml";
				Policy policy = Policy.getInstance(path); // antisamy.xml采用官方给出的ｅｂａｙ的模板
				AntiSamy as = new AntiSamy(policy);
				String content = data.toString();
				if ("0".equals(pattern)) {
					content = StringEscapeUtils.escapeHtml(content);
				}
				// clean content
				CleanResults cr = as.scan(content);
				content = cr.getCleanHTML();
				return content;

			} catch (Exception e) {
				e.printStackTrace();
				return "ScanException,系统错误";
			} 

		}
	}
}